<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class OrderChart extends BaseModel
{
    protected $table = "order_charts";

    public static function updateByDate($date)
    {
        $whereSql = ' deleted_at is null and is_pay="yes" and created_at >="'.$date.' 00:00:00" and created_at <="'.$date.' 23:59:59" ';

        $sql = [];

        //全部订单量和总额
        $sql[0] = 'select count(id) as total,sum(total_fee) as total_fee_sum from orders where '.$whereSql;

        //微信订单
        $sql[1] = 'select count(id) as total,sum(total_fee) as total_fee_sum from orders where `pay_method`=1 and '.$whereSql;

        //积分订单
        $sql[2] = 'select count(id) as total,sum(total_fee) as total_fee_sum from orders where `pay_method`=2 and '.$whereSql;

        $rows = [];

        foreach ($sql as $k=>$v){
            $res = DB::select($v);
            $rows[$k] = $res[0];
        }

        $data = [
            'total' => $rows[0]->total,
            'total_fee' => $rows[0]->total_fee_sum ?:0,
            'general_quantity' => $rows[1]->total,
            'general_fee' => $rows[1]->total_fee_sum ?:0,
            'gift_quantity' => $rows[2]->total,
            'gift_fee' => $rows[2]->total_fee_sum ?:0,
            'qr_general_quantity' => 0,
            'qr_general_fee' =>0,
            'qr_gift_quantity' => 0,
            'qr_gift_fee' => 0,
        ];

        return OrderChart::updateOrCreate(['date'=>$date],$data);
    }
}
